package com.linkage.educloud.ah.mvp.presenter;

import android.content.Context;
import android.content.DialogInterface;
import android.view.View;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.adapter.LoginRoleAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.Child;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.data.WsContentResovler;
import com.linkage.educloud.ah.http.Method;
import com.linkage.educloud.ah.http.RequestUtil;
import com.linkage.educloud.ah.mvp.contract.ILoginContract;
import com.linkage.educloud.ah.mvp.model.LoginModel;
import com.linkage.educloud.ah.widget.CommonDialog;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.BaseSubscriber;
import com.zzhou.common.library.util.LogUtils;
import com.zzhou.common.library.util.StringUtil;
import com.zzhou.common.library.util.SystemTool;
import com.zzhou.common.library.util.ToastShow;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;


/**
 * <desc>
 * Created by The Moss on 2018/7/26.
 */

public class LoginPresenter extends ILoginContract.IPresenter<ILoginContract.IView> {
    ILoginContract.IModel iModel;

    Context mContext;
    CommonDialog mDialog;

    int userType;

    public LoginPresenter(Context context, ILoginContract.IView iView) {
        super(iView);
        mContext = context;
        iModel = new LoginModel();
    }

    @Override
    public void validateAccount(String account) {
//        {"is_first_install":"1","ret":0,"citycode":340100,"user_role":"0","create_date":"","audit_date":"","teacher_statu":"1","parent_statu":"1","cityname":"合肥","msg":"成功","cityid":11}
        Observable observable = iModel.request(Method.POST, false, RequestUtil.validateAccount(account));
        observable.compose(iView.bindLifecycle())
                .subscribe(new BaseSubscriber<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ((ILoginContract.IView) iView).onValidateResult(false, e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (json.getInt("ret") == 0) {
                                int isFirstInstall = json.getInt("is_first_install");
                                int parentStatus = json.getInt("parent_statu");
                                int teacherStatus = json.getInt("teacher_statu");
                                userType = json.getInt("user_role");
                                if (teacherStatus == 4 || parentStatus == 6) {
                                    ((ILoginContract.IView) iView).onValidateResult(false, 1);//验证不通过，提示注册
                                    mDialog = new CommonDialog(mContext, "温馨提示",
                                            "您还不是和教育用户，现在去注册吧。", "好的", "暂不");
                                    mDialog.setOkListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            ToastShow.show(mContext, "该账号非和教育用户，请先注册");
                                            mDialog.dismiss();
                                        }
                                    });
                                    mDialog.setCancelListener(new View.OnClickListener() {
                                        public void onClick(View v) {
                                            // TODO: 2018/8/24 跳到注册页面
                                        }
                                    });
                                    mDialog.show();
                                } else if (isFirstInstall == 0) {//账号从无登陆过，判断为第一次使用，提示修改密码
                                    ((ILoginContract.IView) iView).onValidateResult(true, 2);//验证通过，提示修改密码
                                    mDialog = new CommonDialog(
                                            mContext, "温馨提示",
                                            "您尚未登录过和教育平台，是否先设置密码？", "好的", "暂不");
                                    mDialog.setOkListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            mDialog.dismiss();
                                        }
                                    });
                                    mDialog.setCancelListener(new View.OnClickListener() {
                                        public void onClick(View v) {
                                            // TODO: 2018/8/24 跳到修改密码页面
                                        }
                                    });
                                    mDialog.show();
                                } else {
                                    ((ILoginContract.IView) iView).onValidateResult(true, 0);//0验证通过，可以登录
                                }
                            } else {
                                ToastShow.show(mContext, json.getString("msg"));
                                ((ILoginContract.IView) iView).onValidateResult(false, json.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastShow.show(mContext, e.getMessage());
                            ((ILoginContract.IView) iView).onValidateResult(false, e.getMessage());
                        }
                    }
                });
    }

    @Override
    public void login(final String account, final String pass, int loginType) {
        final int finalLoginType = loginType++;//因为logintype取值0 ，1  参数为1,2所以在这里加1
        String IMEI = SystemTool.getPhoneIMEI(mContext);
        if (IMEI == null) {
            IMEI = android.os.Build.MODEL;
        }
        if (IMEI == null) {
            IMEI = "";
        }
        String verNo = SystemTool.getAppVersionCode(mContext) + "";
        String netType = SystemTool.getNetworkType(mContext);
        final String info = android.os.Build.MODEL + ","
                + android.os.Build.VERSION.RELEASE + ","
                + Constants.DEVICE + verNo + "," + netType + "," + IMEI;
        if (userType == Constants.UserType.DOUBLE) {
            final LoginRoleAdapter adapter = new LoginRoleAdapter(mContext, new LoginRoleAdapter.ItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    mDialog.dismiss();
                    doLogin(account, pass, finalLoginType, info);
                }
            });
            mDialog = new CommonDialog(mContext, "请选择登录角色", adapter, null, "", "");
            mDialog.setCanceledOnTouchOutside(true);
            mDialog.show();
            mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    ((ILoginContract.IView) iView).onLoginResult(false, "没选择角色，请选择角色登录");
                }
            });
        } else {
            doLogin(account, pass, finalLoginType, info);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void getLastLoginAccounts() {
        Observable<List<AccountData>> observable = iModel.lastLoginAccount();
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(iView.bindLifecycle())
                .subscribe(new Consumer<List<AccountData>>() {
                    @Override
                    public void accept(List<AccountData> datas) throws Exception {
                        if (datas == null || datas.size() < 1) {
                            ((ILoginContract.IView) iView).getLastLoginAccount(null);
                            ((ILoginContract.IView) iView).getLastLoginAccounts(null);
                        }
                        ((ILoginContract.IView) iView).getLastLoginAccount(datas.get(0));
                        ((ILoginContract.IView) iView).getLastLoginAccounts(datas);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ((ILoginContract.IView) iView).getLastLoginAccount(null);
                        ((ILoginContract.IView) iView).getLastLoginAccounts(null);
                    }
                });

    }

    @SuppressWarnings("unchecked")
    @Override
    public void valudateAccountLocal(String input) {
//        Observable<AccountData> observable = iModel.queryAccount(input);
        Observable observable = Observable.just(input)
                .filter(new Predicate<String>() {
                    @Override
                    public boolean test(String s) throws Exception {
                        if (StringUtil.isNullOrEmpty(s) || s.length() < 6 || s.length() > 11
                                || !StringUtil.isNumeric(s)) {//账号最短不会小于6位,且为纯数字
                            ((ILoginContract.IView) iView).getAccountByInput(null);
                            return false;
                        }
                        if (s.startsWith("2")) {//账号有2种，一种手机登录，一种为2开头的教师账号
                            return true;
                        }
                        if (s.startsWith("1") && StringUtil.isPhoneNumber(s)) {
                            return true;
                        }
                        ((ILoginContract.IView) iView).getAccountByInput(null);
                        return false;
                    }
                });
        observable.observeOn(AndroidSchedulers.mainThread())
                .compose(iView.bindLifecycle())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String account) throws Exception {
                        AccountData accountData = MyApplication.getInstance().getResovler().getAccountByAccount(account);
                        ((ILoginContract.IView) iView).getAccountByInput(accountData);
                    }
                });
    }

    @SuppressWarnings("unchecked")
    @Override
    public void sendSmsCode(String account) {
        Observable<String> observable = iModel.request(Method.POST, false, RequestUtil.getSmsCode(account));
        observable.compose(iView.bindLifecycle())
                .subscribe(new BaseSubscriber<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastShow.show(mContext, e.getMessage());
                        ((ILoginContract.IView) iView).onSendSmsCodeResult(false);
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (json.getInt("ret") == 0) {
                                ((ILoginContract.IView) iView).onSendSmsCodeResult(true);
                            } else {
                                ToastShow.show(mContext, json.getString("msg"));
                                ((ILoginContract.IView) iView).onSendSmsCodeResult(false);
                            }
                        } catch (JSONException e) {
                            ToastShow.show(mContext, e.getMessage());
                            ((ILoginContract.IView) iView).onSendSmsCodeResult(false);
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void doLogin(final String account, final String pass, int loginType, String info) {
        Observable observable = iModel.request(Method.POST, false,
                RequestUtil.login(loginType, userType, account, pass, info));
        observable.compose(iView.bindLifecycle())
                .subscribe(new BaseSubscriber<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ((ILoginContract.IView) iView).onLoginResult(false, e.getMessage());
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (json.getInt("ret") == 0) {
                                AccountData accountData = AccountData.fromJSONObject(json.getJSONObject("data"));
                                if (accountData == null) {
                                    ((ILoginContract.IView) iView).onLoginResult(false, json.getString("用户信息异常，请联系客服"));
                                    return;
                                }
                                WsContentResovler resovler = MyApplication.getInstance().getResovler();
                                accountData.setLoginAccount(account);
                                accountData.setLoginpwd(pass);
                                accountData.setLoginUser(1);
                                accountData.setlastLoginTime(System.currentTimeMillis());
                                resovler.clearLoginAccount();
                                resovler.insertOrUpdateAccount(accountData.getLoginAccount(), accountData);
                                resovler.clearChild();
                                for (Child child : accountData.getStudentData()) {
                                    LogUtils.e("**********************" + child.getName());
                                    resovler.insertChild(accountData.getLoginAccount(), child);
                                }
                                AccountConfig.notifyAccountChanged();
                                ((ILoginContract.IView) iView).onLoginResult(true, json.getString("msg"));
                            } else {
                                ((ILoginContract.IView) iView).onLoginResult(false, json.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ((ILoginContract.IView) iView).onLoginResult(false, e.getMessage());
                        }
                    }
                });
    }
}
